use actix_web::{HttpServer, App};
use secret::controller;
use secret::util::logger;
use secret::base;
use std::sync::mpsc;
use std::{thread, env};
use actix_web::rt::System;

#[actix_web::main]
async fn main() {
    println!("current mac address `{}`", base::MAC_ADDRESS.as_str());
    let args: Vec<String> = env::args().collect();
    let mut port = 7789;
    if args.is_empty() || args.get(1).is_none() {
        println!("using default port : {}", port);
    } else {
        port = args.get(1).unwrap().parse::<i32>().unwrap();
        println!("using port : {}", port);
    }

    logger::init_log(true);

    controller::init_time_server();

    let (tx, rx) = mpsc::channel();
    thread::spawn(move || {
        let sys = System::new("http-server");
        let srv = HttpServer::new(|| {
            App::new()
                .service(controller::get_current_base_file)
                .service(controller::import_time)
        })
            .bind(format!("0.0.0.0:{}", port))?
            .run();
        let _ = tx.send(srv);
        sys.run()
    });
    let srv = rx.recv().unwrap();
    loop {
        if !base::BQ.pop(0, 500 * 1000 * 1000) {
            srv.stop(true).await;
            break;
        }
    }
}